<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>列表渲染练习</title>
  </head>
  <body>
<div id="app">
  <input type="text" placeholder="可汗大点兵" @keyup.enter="searchPersons" />

  <ul>
    <li v-for="person in newPersons" :key="person.id">
      {{person.name}} - {{person.age}}
    </li>
  </ul>

  <button @click="sortBy ='asc'">年龄升序</button>
  <button @click="sortBy ='desc'">年龄降序</button>
  <button @click="sortBy =''">原本顺序</button>
</div>

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
const vm = new Vue({
  el: '#app',
  data: {
    persons: [
      { id: 1, name: "甲", age: 30 },
      { id: 2, name: "乙", age: 41 },
      { id: 3, name: "丙", age: 18 },
      { id: 4, name: "丁", age: 29 },
    ],
    searchText: "",
    sortBy: "",
  },
  methods: {
    //搜索触发的函数
    searchPersons(e) {
      this.searchText = e.target.value;
    },
  },
  computed: {
    newPersons() {
      //计算属性
      //过滤
      const filteredPersons = this.persons.filter((person) =>
        person.name.includes(this.searchText)
      );
      //排序
      if (this.sortBy) {
        filteredPersons.sort((a, b) =>
          this.sortBy === "asc" ? a.age - b.age : b.age - a.age
        );
      }
      //返回值
      return filteredPersons;
    },
  },
});
</script>
  </body>
</html>
